import {defineStore} from 'pinia'
import {Dictionary} from '@/api/config'
import {DicItem, getDicData as getDic} from '@/api/login'
import {getFieldRequired} from '@/api/medicalExaminerDesk/medicalExaminerDesk'
import {getLocalData, setLocalData} from '@/util/dkmk'
interface CommonState {
  dicData: Dictionary<Array<DicItem>> | null
  fields: Array<string>
  situation: string | null
}

const commonStore = defineStore('commonStore', {
  state: (): CommonState => {
    return {
      dicData: null,
      fields: [],
      situation: getLocalData('Situation') || 'inner'
    }
  },
  getters: {
    getSyncDicData() {
      return (dicName: string): Array<DicItem> | null => {
        if (!this.dicData) return null
        return this.dicData[dicName] ? this.dicData[dicName] : null
      }
    }
  },
  actions: {
    setDicData(dicName: string, data: Array<DicItem>) {
      if (!this.dicData) this.dicData = {}
      this.dicData[dicName] = data
    },
    getDicData(dicName: string, refresh?: boolean) {
      return new Promise<Array<DicItem> | null>((resolve, reject) => {
        const dicData = this.getSyncDicData(dicName)
        if (dicData && !refresh) {
          resolve(dicData)
        } else {
          getDic({dictCodes: dicName})
            .then((res) => {
              const dicData = res.data.data && res.data.data[0] ? res.data.data[0].items : []
              this.setDicData(dicName, dicData)
              resolve(dicData)
            })
            .catch((error) => {
              reject(error)
            })
        }
      })
    },
    /**
     * @description: 设置校验字段
     * @param {Array} data
     * @return {*}
     */
    setFields(data: Array<string>) {
      if (!this.fields) this.fields = []
      this.fields = data || []
    },
    /**
     * @description: 获取校验字段
     * @return {*}
     */
    getFields() {
      return new Promise<Array<string> | null>((resolve, reject) => {
        getFieldRequired()
          .then((res) => {
            const {data} = res.data
            this.setFields(data || [])
            resolve(data || [])
          })
          .catch((error) => {
            this.setFields([])
            reject(error)
          })
      })
    },
    /**
     * @description: 设置修改内外网环境
     * @param {string} data inner 内网 outer 外网
     * @return {*}
     */
    setSituation(data: string) {
      if (!this.situation) this.situation = null
      setLocalData('Situation', data)
      this.situation = data
    }
  }
})

export default {
  setup() {
    const store = commonStore()
    const reset = () => {
      store.dicData = null
    }
    return {store, reset}
  }
}
